<template>
  <div class="zhu2">
    <Nav></Nav>
    <HeadNava :type="1"></HeadNava>
    <el-card class="box-card dindan_zhu" shadow="never">
      <div slot="header" class="clearfix ">
        <span>选择收货地址</span>
      </div>

      <div class="text item xz_dizi">
        <el-card
          v-for="item in this.show_tableData"
          :key="item.addressId"
          shadow="hover"
          class="box-card dizhi_card"
          v-on:mouseover.native="changeActive(item.type, $event)"
          v-on:mouseout.native="removeActive(item.type, $event)"
          v-on:click.native="change_dz(item, $event)"
          :class="item.type == 1 ? 'bored_color' : ''"
        >
          <div slot="header" class="clearfix dizhi_name ">
            <el-button
              class="name_xz"
              style="  float:right;font-size:4px;"
              type="text"
              size="mini"
              v-if="item.addressDefault == 1"
              >默认地址</el-button
            >

            <span
              >{{ item.receiveCounty.replace("市", "").replace("区", "")
              }}{{ item.receiveCity.replace("区", "").replace("市", "") }}（{{
                item.receiveName
              }}）</span
            >
          </div>
          <div class="text item dizhi_item">
            {{ item.receivePhoneNumber }}{{ item.receiveDesc }}<br />
            <el-button type="text"  @click="handleEdit(item)"
              style=" font-size:10px ;color:#F9CC9D; margin-bottom:30px;"
              v-if="item.type == 1"> 修改</el-button>
            <!-- <h6
              @click="handleEdit(item)"
              style="font-size:10px ;color:#F9CC9D; margin-bottom:30px;"
              v-if="item.type == 1"
            >
              修改
            </h6> -->
          </div>
        </el-card>
      </div>
      <div class="xz_quanbu">
        <el-link
          disabled
          style="float:left;margin-left: 27px;"
          @click.native="show"
          >{{
            this.show_dizhi == 0 && this.tableData.length > 4
              ? "显示全部"
              : "使用新地址"
          }}</el-link
        >

        <router-link :to="{ path: '/userhome/user_dizhi' }">
          <span style="float:right; margin-right:px"
            >管理收货地址</span
          ></router-link
        >
      </div>
    </el-card>
    <el-card class="box-card dindan_zhu" shadow="never">
      <div slot="header" class="clearfix ">
        <span>确认订单信息</span>
      </div>
      <div class="text item xz_dizi">
        <el-table
          ref="multipleTable"
          :data="book_list"
          tooltip-effect="dark"
          @select="selectCall()"
          style="width: 100%"
        >
          <el-table-column width="110" align="center">
            <template slot-scope="scope">
              <el-image
                style="height: 120px"
                :src=" scope.row.img"
              >
                <!-- <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div> -->
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="书名" width="180">
          </el-table-column>
          <el-table-column prop="author" label="作者" width="180">
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template slot-scope="scope">
              <p>￥{{ scope.row.price }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="数量" width="250" align="center">
          </el-table-column>
          <el-table-column label="优惠" prop="status" width="120">
          </el-table-column>
          <el-table-column label="小计" width="170" fixed="right">
            <template slot-scope="scope">
              <p style="color: red">
                {{ scope.row.price * scope.row.count}}元
              </p>
            </template>
          </el-table-column>

          <!-- <template slot-scope="scope">
              <i class="el-icon-delete" style="font-size: 25px;"></i>
            </template> -->
        </el-table>
      </div>
    </el-card>
    <div class="tijiao">
      <span>普通配送 快递 免邮&nbsp;&nbsp;&nbsp;</span>
      <span style="font-weight: 700;">实付款：</span
      ><span style=" color:#999999 ; font-size:25px">￥</span
      ><span class="tijiao_price">{{ this.price }}</span
      ><br /><br />
      <span style="font-weight: 700;">寄送至：</span
      ><span style="font-size:10px">
        {{ this.dz_moren.receiveProvince }} {{ this.dz_moren.receiveCity }}
        {{ this.dz_moren.receiveCounty }} {{ this.dz_moren.receiveDesc }}</span
      ><br />
      <span style="font-weight: 700;">收货人：</span
      ><span
        >{{ this.dz_moren.receiveName }}
        {{ this.dz_moren.receivePhoneNumber }}</span
      >
    </div>
    <div class="jiesuan1">
      <router-link :to="{ path: '/user_gwc' }">
        <span class="jiesuan1_12 el-icon-shopping-cart-2"
          >返回购物车</span
        ></router-link
      >

      <div class="jiesuan1_11" @click="tijiao1">提交订单</div>
    </div>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <Dizhi
        :dizhi="this.dizhi1"
        :tableData="this.show_tableData"
        :type_1="this.type_1"
        :dialogVisible="this.dialogVisible"
        @guanbi="this.guanbi"
        @xz_dizi="this.xz_dz"
      ></Dizhi>

    
    </el-dialog>
    <!-- 选择支付方式 -->
    <el-dialog
      title="选择支付方式"
      :visible.sync="dialogVisible_pay"
      width="30%"
      height="600px"
      :before-close="handleClose"
      class="dindan_pay"
    >
      <el-dialog
        title="余额支付"
        :visible.sync="showKeyboard"
        append-to-body
        width="20%"
      >
        <el-input
          placeholder="请输入密码"
          v-model="password"
          show-password
          autocomplete="off"
        ></el-input>

        <div slot="footer" class="dialog-footer">
          <el-button @click="showKeyboard = false">取 消</el-button>
          <el-button type="primary" @click="yue_qd()">确 定</el-button>
        </div>
      </el-dialog>
      <a @click="zfb" class="pay_type">
        <img
          style="width: 100px; height: 100px; margin-top:0px "
          src="../../assets/zfb.jpg"
          alt=""
        />
        <p>支付宝</p>
      </a>
      <a @click="ye" class="pay_type">
        <img
          style="width: 100px; height: 100px; margin-top:0px "
          src="https://storage.360buyimg.com/payment-assets/sdk/bank/XJKCONSUME.png"
          alt=""
        />
        <p>余额支付</p>
      </a>
      <a @click="wx" class="pay_type">
        <img
          style="width: 100px; height: 100px; margin-top:0px "
          src="//storage.360buyimg.com/payment-assets/sdk/bank/PAY-WEIXIN.png"
          alt=""
        />
        <p>微信支付</p>
      </a>
      <a slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_pay = false">取 消</el-button>
      </a>
    </el-dialog>
  </div>
</template>

<script>
import Nav from "../../com/components/Common/Nav.vue";
import Dizhi from "../../com/components/Common/dizhi.vue";
import HeadNava from "../../com/components/Common/HeadNava";
import axios from "axios";
import VDistpicker from "v-distpicker";
import Qs from "qs";
export default {
  components: { Nav, HeadNava, VDistpicker, Dizhi },
  data() {
    var checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("不能为空"));
      } else {
        callback();
      }
    };
    var checkName1 = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("不能为空"));
      } else {
        callback();
      }
    };

    var checkNumber = (rule, value, callback) => {
      var regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!value) {
        return callback(new Error("手机号不能为空"));
      }

      if (!Number.isInteger(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (!regMobile.test(value)) {
          callback(new Error("请输入有效的11位手机号码！"));
        } else {
          callback();
        }
      }
    };
    return {
      password: "",
      showKeyboard: false,
      orderId: "",
      type_1: 1, //修改及添加地址的状态
      show_dizhi: 0, //是否显示全部地址
      Data: [], //后端原始地址数组
      price: "", //总价格
      dialogVisible: false,
      dialogVisible_pay: false,
      dizhi1: {},
      dizhi_type: 1,
      xz_type: 0,
      dz_moren: {
        status: 0,
      },
      tableData: [],
      show_tableData: [],
      book_list: [],
      formLabelAlign: {
        name: "",
        phoneNumber: "",
        yzbm: "",
        Province: "",
        County: "",
        City: "",
        Desc: "",
        addressId: "",
        index: "",
      },
      rules: {
        phoneNumber: [{ validator: checkNumber, trigger: "blur" }],
        name: [{ validator: checkName, trigger: "blur" }],
        Desc: [{ validator: checkName1, trigger: "blur" }],
      },
    };
  },
  methods: {
    zfb() {
      ;

      var params = new URLSearchParams();
      params.append("userId", this.userInfo.userId);
      params.append("addressId", this.dz_moren.addressId);
      axios.post("//fl-bookOrder/createOrderByCart", params).then((res) => {
        if (res.data.code == 200) {
          ;
          this.$message({
            message: "订单已成功生成，正在为您跳转支付地址",
            type: "success",
          });
          ;
          //获取生成订单的id
          ;

          this.orderId = res.data.data[res.data.data.length - 1].order.orderId;

          window.open(
            "https://end.flya.top/aliPay/pcPay?orderId=" + this.orderId + "&type=1",
            "_parent"
          );
          // window.showModalDialog('/aliPay/pcPay?orderId='+this.orderId,window)
        } else {
          this.$message({
            showClose: true,
            message: "该购物车的订单已经提交啦",
            type: "warning",
          });
        }
      });

      //根据订单id查询订单支付状态
      //如果未支付则让页面跳转支付页面

      //查询用户支付结果
      //     //成功则router跳转到订单详情页面
    },
    ye() {
      ;
      this.$message({
        showClose: true,
        message: "正在支付，请稍后",
      });
      ;
      if (this.userInfo.accountBalance < this.price) {
        this.$confirm("您的余额不足是否充值?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$router.push("/pay");
            this.$message({
              type: "success",
              message: "请充值!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
      } else {
        this.showKeyboard = true;
        var params = new URLSearchParams();
      params.append("userId", this.userInfo.userId);
      params.append("addressId", this.dz_moren.addressId);

      axios.post("/fl-bookOrder/createOrderByCart", params).then((res) => {
        //获取生成订单的id
        ;
        if (res.data.code == 200) {
          this.$message({
            message: "订单已成功生成",
            type: "success",
          });
          ;

          this.orderId = res.data.data[res.data.data.length - 1].order.orderId;
         
        } else {
          this.$message({
            showClose: true,
            message: "该购物车的订单已经提交啦",
            type: "warning",
          });
        }
      });
      }
    },
    yue_qd() {
       let params = new URLSearchParams();
          params.append("orderId", this.orderId);
          params.append("userId", this.userInfo.userId);
          params.append("payPassword", this.password);
          axios
            .post("/fl-bookOrder/payForOrderByBalance", params)
            .then((res) => {
              ;
              if (res.data.code == 200) {
                this.$message({
                  message: "支付成功",
                  type: "success",
                });
                setTimeout(() => {
                this.$router.push({
                path: "/userhome/dindan_xq",
                query: {
                  id: this.orderId,
                },
              });
                }, 1000);
                 
              }else{
                this.$message({
                  message: "支付密码输入错误",
                  type: "error",
                });
                
              }
             
            });
    },
    wx() {
      ;
    },
    tijiao1() {
      ;
      if (this.dz_moren.status == 0) {
        this.$message({
          message: "您还没有选择收货地址哦",
          type: "warning",
        });
      } else {
        //选择支付方式
        this.dialogVisible_pay = true;
      }

      //   var params = new URLSearchParams();
      //   params.append('userId', this.userInfo.userId);
      //   params.append('addressId',this.dz_moren.addressId );
      // axios
      //   .post("//fl-bookOrder/createOrderByCart", params).then((res)=>{
      //     //获取生成订单的id
      //     
      //    this.orderId=res.data.data[res.data.data.length -1].order.orderId
      //     window.open('/aliPay/pcPay?orderId='+this.orderId,window)
      //     // window.showModalDialog('/aliPay/pcPay?orderId='+this.orderId,window)
      //   })

      //      setTimeout(() => {
      //    window.opener.location.href ='http://localhost:8080/#/index'
      //       
      //      },20000)
      //     //根据订单id查询订单支付状态
      //     //如果未支付则让页面跳转支付页面

      //     //查询用户支付结果
      //     //成功则router跳转到订单详情页面
    },

    show() {
      //显示全部
      if (this.show_dizhi == 1) {
        this.dialogVisible = true;
      }
      this.show_dizhi = 1;

      this.type_1 = 1;
      ;
    },

    handleEdit(val) {
      this.dialogVisible = true;
      ;
      this.dizhi1 = val;
      this.type_1 = 0;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    changeActive(i, $event) {
      $event.currentTarget.className = "box-card dizhi_card  bored_color";
    },
    removeActive(i, $event) {
      if (i == 0) {
        $event.currentTarget.className = "box-card dizhi_card ";
        ;
      }
    },
    change_dz(i, $event) {
      ;
      $event.currentTarget.className = "box-card dizhi_card  bored_color";
      for (let item of this.show_tableData) {
        item.type = 0;
      }

      i.type = 1;
      this.xz_dz();
      ;
    },
    xz_dz() {
      //选择默认地址

      this.show_tableData.forEach((item) => {
        ;
        if (item.type == 1) {
          this.dz_moren = item;
          this.dz_moren.status = 1;
        }
      });
      ;
    },
  
    paixu(ary, key) {
      //排序数组函数
      return ary.sort(function(a, b) {
        let x = a[key];
        let y = b[key];
        return x > y ? -1 : x < y ? 1 : 0;
      });
    },

    getdizhilist() {
      //获取用户收货地址
      this.loading = true;
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
      axios
        .get("/fl-address/getAddressByUserId", {
          params: {
            userId: this.userInfo.userId,
          },
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          res.data.data.forEach((index, i) => {
            if (index.addressDefault == 1) {
              //添加地址是否被选中属性
              this.$set(res.data.data[i], "type", 1);
            } else this.$set(res.data.data[i], "type", 0);
          });
          this.tableData = this.paixu(res.data.data, "addressDefault"); //排序数组使默认地址排在第一
          this.Data = this.paixu(res.data.data, "addressDefault");
          ;

          if (this.show_dizhi == 1) {
            this.show_tableData = this.tableData.filter(
              (
                item,
                index //筛选数组只显示4个地址
              ) => index > -1
            );
          } else
            this.show_tableData = this.tableData.filter(
              (
                item,
                index //筛选数组只显示4个地址
              ) => index > -1 && index < 4
            );
          this.xz_dz(); //初始化提交订单默认地址
          // this.loading = false;
        });
    },
    getprice() {
      var params = new URLSearchParams();
      params.append("username", this.userInfo.username);
      axios
        .post("/fl-carts/getUserTotalCartsPrice", params, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          ;
          this.price = res.data.data.replace("元", "");
        });
    },
    guanbi() {
      this.dialogVisible = false;
    },
  },
  updated() {
    // 
  },
  created() {
    this.book_list = this.$route.query.xz_list;
    this.book_list = JSON.parse(localStorage.getItem("order_list"));

    this.getdizhilist();
    this.getprice();

    // 
  },
  watch: {
    show_dizhi() {
      ;

      if (this.show_dizhi == 1) {
        this.show_tableData = this.tableData.filter(
          (
            item,
            index //筛选数组只显示4个地址
          ) => index > -1
        );
      } else
        this.show_tableData = this.Data.filter(
          (
            item,
            index //筛选数组只显示4个地址
          ) => index > -1 && index < 4
        );
    },
  },
};
</script>

<style lang="less">
.xz_quanbu {
  height: 30px;
  line-height: 20px;
  width: 100%;
  margin-bottom: 0;

  span {
    cursor: pointer;
    position: relative;
    margin-right: 0;
  }
}
.dindan_zhu {
  width: 60%;

  margin-left: 19%;

  .xz_dizi {
    border: 1px solid #fff;
    position: relative;
    margin-bottom: 0;
    width: 100%;
    display: inline-block;

    h3 {
      margin-left: -89%;
      margin-bottom: 10px;
      font-weight: 700;
      font-size: 15px;
    }

    .dizhi_card {
      margin-bottom: 10px;
      width: 230px;
      border: 3px solid #ddd;
      margin-left: 30px;
      float: left;
      cursor: pointer;
      border-image: -webkit-linear-gradient(rgb(75, 75, 75), rgb(174, 177, 176))
        20 20;
      border-image: -moz-linear-gradient(rgb(75, 75, 75), rgb(174, 177, 176)) 20
        20;
      border-image: -o-linear-gradient(rgb(75, 75, 75), rgb(174, 177, 176)) 20
        20;
      border-image: linear-gradient(rgb(75, 75, 75), rgb(174, 177, 176)) 20 20;
    }

    .bored_color {
      width: 230px;
      border: 3px solid #ddd;
      margin-left: 30px;
      border-image: -webkit-linear-gradient(#f80, #2ed) 20 20;
      border-image: -moz-linear-gradient(#f80, #2ed) 20 20;
      border-image: -o-linear-gradient(#f80, #2ed) 20 20;
      border-image: linear-gradient(#f80, #2ed) 20 20;
    }

    .dizhi_name {
      height: 1px;
      line-height: 10px;
      color: #666666;
      font-weight: 700;
      position: relative;
      .name_xz {
        position: absolute;
        float: right;
        left: 152px;
        top: -18px;
        font-size: 6px;
        background: rgb(224, 220, 220);
        width: 60px;
        color: #fff;
        text-align-top: 0px;
        height: 20px;
      }
    }
    .dizhi_item {
      position: relative;
      height: 20px;
      line-height: 20px;
      margin-top: -15px;
      margin-bottom: 40px;
      font-size: 10px;
      float: none;
    }
  }

  .dindan_queren {
    width: 1200px;
    position: relative;

    h3 {
      margin-left: -89%;
      margin-bottom: 10px;
      font-weight: 700;
      font-size: 15px;
    }
  }
}
.tijiao {
  text-align: right;
  width: 410px;
  height: 120px;
  border: 1px solid rgb(194, 18, 18);
  -webkit-box-shadow: 0px 1px 3px rgb(194, 18, 18) inset;

  -moz-box-shadow: 0px 1px 1px rgb(194, 18, 18) inset;

  box-shadow: 0px 0px 3px rgb(194, 18, 18) inset;
  position: relative;

  float: right;
  margin-right: 21%;
  padding-top: 20px;
  padding-right: 10px;
  .tijiao_price {
    font-weight: 700;
    font-size: 25px;

    color: #ff0036;
  }
}
.jiesuan1 {
  text-align: right;
  width: 1800px;
  float: right;
  position: relative;
  cursor: pointer;
  height: 60px;
  margin-right: 21%;
  .fanhui_dindan {
    left: 300px;
  }
  .jiesuan1_12 {
    height: 40px;
    line-height: 40px;
    margin-right: 100px;
    cursor: pointer;
  }
  .jiesuan1_11 {
    float: right;
    width: 150px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #ffffff;
    font-weight: 700;
    background: #ff0036;

    padding-left: 30px;
  }
}
.dizhi_bianji {
  position: relative;
  .bianji_tou {
    width: 790px;
    height: 30px;
    line-height: 30px;
    background: #409eff;
    margin-bottom: 20px;
  }
  .baocun_tou {
    width: 790px;
    height: 30px;
    line-height: 30px;
    background: #f3f8fe;
    margin-bottom: 20px;
  }

  .form_dizhi {
    width: 450px;
    margin-bottom: 5px;
  }
  .dizhi_xz {
    height: 10px;
  }
}
.dindan_pay {
  .pay_type {
    display: inline-block;
    margin-left: 50px;

    p {
      font-size: 15px;
      text-align: center;
    }
  }
}
</style>
